/*
对话聊天的路由组件
 */

import React, {Component} from 'react'
import {NavBar, List, InputItem, Grid, Icon} from 'antd-mobile'
import {connect} from 'react-redux'
import QueueAnim from 'rc-queue-anim'

import {sendMsg, readMsg} from '../../redux/actions'

const Item = List.Item

class Chat extends Component {

  state = {
    content: '',
    isShow: false
  }
  handleSend = ()=>{
    const from = this.props.user._id
    const to = this.props.match.params.userId
    const content = this.state.content.trim()
    // 发送请求
    if(content){
      this.props.sendMsg({from, to, content})
    }
    // 清除输入框数据
    this.setState({content:'', isShow: false})
  }

  toggleShow = () => {
    const isShow = !this.state.isShow
    this.setState({isShow})
    if(isShow) {
      // 异步手动派发resize事件,解决表情列表显示的bug
      setTimeout(() => {
        window.dispatchEvent(new Event('resize'))
      }, 0)
    }
  }

  // 在第一次render()之前回调
  componentWillMount () {
    // 初始化表情列表数据
    const emojis = ['😀', '😁', '🤣','😀', '😁', '🤣','😀', '😁', '🤣','😀', '😁', '🤣','😀'
      ,'😁', '🤣','😀', '😁', '🤣','😀', '😁', '🤣','😀', '😁', '🤣'
      ,'😁', '🤣','😀', '😁', '🤣','😀', '😁', '🤣','😀', '😁', '🤣'
      ,'😁', '🤣','😀', '😁', '🤣','😀', '😁', '🤣','😀', '😁', '🤣']
    this.emojis = emojis.map(emoji => ({text: emoji}))
  }
  componentDidMount() {
    // 初始显示列表 消息滑倒底部
    window.scrollTo(0, document.body.scrollHeight)
    // 发请求更新消息的未读信息
    const from = this.props.match.params.userId
    const to = this.props.user._id
    this.props.readMsg(from, to)

  }
  componentDidUpdate () {
    // 更新显示列表
    window.scrollTo(0, document.body.scrollHeight)
  }
  componentWillUnmount(){
     // 发请求更新消息的未读信息
     const from = this.props.match.params.userId
     const to = this.props.user._id
     this.props.readMsg(from, to)
  }


  render() {
    const {user} = this.props
    const {users, chatMsgs} = this.props.chat

    const meId = user._id
    const targetId = this.props.match.params.userId
    const chatId = [meId, targetId].sort().join('_')

    if(!users[meId]) return null
     // 对chatMsg进行过滤
    let msgs = chatMsgs.filter(msg => msg.chat_id === chatId )
    const targetIcon = users[targetId].header ? require(`../../assets/images/${users[targetId].header}.png`).default : null
    // const meHeader = user.header ? require(`../../assets/images/${user.header}.png`).default : null
   console.log(this.state.content)
    return (
      <div id='chat-page'>
        <NavBar
          icon={<Icon type='left' onClick={()=>{this.props.history.goBack()}}/>}
          className='sticky-header'
        >
          {users[targetId].username}
        </NavBar>
        <List style={{marginTop:50, marginBottom: 50}}>
          {/* <QueueAnim type='alpha'> */}
          {
            msgs.map((msg)=>{
              if(msg.from !== targetId){
                return (
                  <Item 
                    className='chat-me'
                    extra='我'
                    key={msg._id}
                    // thumb={meHeader}
                  >
                    {msg.content}
                  </Item>
                )
              }else{
                return (
                  <Item
                    key={msg._id}
                    thumb={targetIcon}
                  >
                    {msg.content}
                  </Item>
                )
              
              }
            })
          }
          {/* </QueueAnim> */}
         
        </List>

        <div className='am-tab-bar'>
          <InputItem
            placeholder="请输入"
            value={this.state.content}
            onChange={(val)=>{this.setState({content: val})}}
            onFocus={()=>{this.setState({isShow: false})}}
            extra={
              <span>
                <span onClick={this.toggleShow} style={{marginRight:5}}>😊</span> &nbsp;
                <span onClick={this.handleSend}>发送</span>
              </span>
            }
          />
          {this.state.isShow ? (
            <Grid
              data={this.emojis}
              columnNum={8}
              carouselMaxRow={4}
              isCarousel={true}
              onClick={(item) => {
                this.setState({content: this.state.content + item.text})
              }}
            />
          ) : null}
        </div>
      </div>
    )
  }
}

export default connect(
  state => ({user: state.user, chat: state.chat}),
  {sendMsg, readMsg }
)(Chat)